<?php
abstract class Backend_Controller_Crud extends Backend_Controller{
    
    public function indexAction()
    {
        $this->_resource->addInlineJs('
        	var canEdit = '.($this->_user->canEdit($this->_module)).';
        	var canDelete = '.($this->_user->canDelete($this->_module)).';
        ');
        
        $media = Model_Medialib::getInstance();
        $media->includeScripts();
        
        $this->_resource->addJsRawFile('/js/lib/tiny_mce/tiny_mce.js');
	    $this->_resource->addJs('/js/lib/ext_ux/Ext.ux.TinyMCE.js' , 0 , true);
	    $this->_resource->addJs('/js/lib/ext_ux/SearchField.js', 0); 
        $this->_resource->addJs('/js/app/system/SearchPanel.js', 0);
        $this->_resource->addJs('/js/app/system/RelatedGridPanel.js' , 0);  
        $this->_resource->addJs('/js/app/system/SelectWindow.js' , 0);       
        $this->_resource->addJs('/js/app/system/HistoryPanel.js', 0);
        $this->_resource->addJs('/js/app/system/EditWindow.js' , 0);    
        $this->_resource->addJs('/js/app/system/crud/'.strtolower($this->_module).'.js', 4);   
    } 
       
    public function listAction()
    {

    }
    /**
     * Read object action
     */
    public function loaddataAction()
    { 	
        $id = Request::post('id', 'integer', false);
        
        if(!$id)
            Response::jsonSuccess(array());
              
        try{
            $obj = new Db_Object($this->_module, $id);
        }catch(Exception $e){
            Response::jsonError($this->_lang->CANT_EXEC);
        }
               
        $data = $obj->getData();
                
        /*
         * Prepare  mltilink properties
         */      
        $fields = $obj->getFields();
        foreach($fields as $field){
            if($field=='id' || empty($data[$field]))
                continue;
            $linkObject = $obj->getLinkedObject($field);
            if($linkObject !== false)
                $data[$field] = array_values($this->_collectLinksData($data[$field] ,$linkObject));
        } 
        $data['id'] = $obj->getId();
        /*
         * Send response
         */
        Response::jsonSuccess($data);
    }
    /**
     * Prepear data for linked field component
     * @param array $data
     * @param string $objectName
     * @return array
     */
    protected function _collectLinksData(array $data , $objectName)
    {           
        $ids = Utils::fetchCol('id', $data);
        $data = Utils::rekey('id', $data);

        $obj = new Db_Object($objectName);
        $model = Model::factory(ucfirst($objectName));
        
        $fields = array('id' , 'title'=>$obj->getConfig()->getLinkTitle());
        $usedRc = $obj->getConfig()->isRevControl();
        if($usedRc)
            $fields[] = 'published';
        
        $odata = $model->getItems($ids , $fields);  
        if(!empty($data))
            $odata = Utils::rekey('id', $odata);
        /*
         * Find out deleted records
         */ 
        $deleted = array_diff($ids, array_keys($odata));  
        
        $deletedData = array();

        $result = array();
        foreach ($ids as $id){
  
            if(in_array($id, $deleted)){
                 $item = array('id'=>$id , 'deleted'=>1 , 'title'=>$data[$id]['title'], 'published'=>1);
                 if($usedRc)
                     $item['published'] = 0;
            } else{
                $item = array('id'=>$id , 'deleted'=>0 , 'title'=>$odata[$id]['title'],'published'=>1);
                if($usedRc){
                     $item['published'] = $odata[$id]['published'];     
                 }
            }
            $result[] = $item;
        }  
        return $result;  
    }
    /**
     * Edit action
     */
    public function editAction()
    {
        $id = Request::post('id', 'integer', false);
        if(!$id)
            $this->createAction();
        else 
            $this->updateAction();    
    }
    /**
     * Create object action
     */
    public function createAction()
    {   	
    	$this->_checkCanEdit();
        self::insertObject(Backend_Controller::getPostedData($this->_module));
    }
    /**
     * Update object action
     */
    public function updateAction()
    { 
         $this->_checkCanEdit();
         self::updateObject(Backend_Controller::getPostedData($this->_module)); 
    }
    /**
     * Delete object action
     */
    public function deleteAction()
    {   
        $id = Request::post('id','integer', false);
            
        try{
        	$object = new Db_Object($this->_module , $id);
        }catch(Exception $e){
        	Response::jsonError($this->_lang->WRONG_REQUEST);
        }
    
         if(!$id)
            Response::jsonError($this->_lang->WRONG_REQUEST);
            
         if(!User_Admin::getInstance()->canDelete($this->_module))
            Response::jsonError($this->_lang->CANT_DELETE);
          
         if($this->_configMain->get('vc_clear_on_delete'))
             Model_Vc::getInstance()->removeItemVc($this->_module , $id);

         if(!$object->delete())
             Response::jsonError($this->_lang->CANT_EXEC);

         Response::jsonSuccess();
    }

    /**
     * Insert Object into DB
     * @param Db_Object $object
     * @return void
     */
    public static function insertObject(Db_Object $object)
    {
         $lang = Lang::getInstance();
         
         if(!$recId = $object->save())
             Response::jsonError($lang->CANT_CREATE);
                                   
          Response::jsonSuccess(array('id'=>$recId,));    
    }
    /**
 	 * Update object
     * @param Db_Object $object
     */
    public static function updateObject(Db_Object $object)
    {                 
        $lang = Lang::getInstance();
                 
        if(!$object->save())
           Response::jsonError($lang->CANT_EXEC); 
             	  
        Response::jsonSuccess(array('id'=>$object->getId()));          
    }
}